<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="resources/css/layui.css">
<script type="text/javascript" src="resources/js/jquery.1.12.4.min.js"></script>
<script type="text/javascript" src="resources/js/layui.js"></script>

<!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>
	<form class="layui-form">
		<div class="layui-form-item" style="margin: 15px; height: 30px;">
			<div
				style="height: 40px; width: 70px; float: left; line-height: 40px;">角色名称:</div>
			<input type="text" class="layui-input"
				style="display: inline-block; width: 250px; float: left;"
				id="keyword" name="keyword" value="" lay-verify=""
				placeholder="请输入角色名" autocomplete="off">
			<div class="layui-input-inline"
				style="width: 150px; text-align: center;">
				<a class="layui-btn" id="search" data-type="reload" name="search">
					<i class="layui-icon"></i>搜索
				</a>
			</div>
			<div style="float: left; width: 380px; height: 40px;">
				<div class="layui-input-inline"
					style="width: 100px; margin-right: 20px;">
					<a class="layui-btn layui-btn-normal" id="add" name="add"> <i
						class="layui-icon">&#xe654;</i>添加角色
					</a>
				</div>
			</div>
		</div>
	</form>
	<div>
		<table id="type" lay-filter="type"></table>
	</div>
	<div id="formData"
		style="width: 300px; display: none; padding-top: 15px;">
		<form class="layui-form" id="roleForm">
			<input type="hidden" name="roleId" id="showRoleId" />
			<div class="layui-form-item">
				<label class="layui-form-label">角色名称</label>
				<div class="layui-input-block">
					<input type="text" name="roleName" id="showRoleNmae" required
						lay-verify="required" value="" class="layui-input" />
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">权限</label>
				<div class="layui-input-block editFunList" lay-verify="funcheck">
					<input type="checkbox" name="" title="暂无" lay-skin="primary"
						disabled>
				</div>
			</div>
		</form>
	</div>
	<div id="addData"
		style="width: 300px; display: none; padding-top: 15px;">
		<form class="layui-form" id="addRoleForm">
			<div class="layui-form-item">
				<label class="layui-form-label">角色名称</label>
				<div class="layui-input-block">
					<input type="text" id="addTypeName" name="roleName" required
						lay-verify="required" value="" class="layui-input" />
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">权限</label>
				<div class="layui-input-block funslist" lay-verify="funcheck">
					<input type="checkbox" name="" title="暂无" lay-skin="primary"
						disabled>
				</div>
			</div>
		</form>
	</div>
	<script type="text/html" id="bar">
    <a class="layui-btn layui-btn-xs layui-btn-normal" title="编辑" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" title="刪除" lay-event="delete">刪除</a>
</script>
	<script type="text/html" id="dateTpl">
    {{ layui.laytpl.fn(d.editdate) }}
</script>
	<script type="text/javascript">
    var table;
    var layer;
    var form;
    layui.use(['layer', 'table', 'form'], function () {
        table = layui.table;
        layer = layui.layer;
        form = layui.form;

        form.verify({
            funcheck: function (value, item) {
                var elem = $(item).find('div.layui-form-checked');
                if (elem.length == 0) {
                    return '请选择权限';
                }
            }
        })
        //--------------方法渲染TABLE----------------
        var tableIns = table.render({
            elem: '#type'
            , id: 'type'
            , url: 'permission/findRolesBySplitPage'
            , width: 684
            , cols: [[
                {checkbox: true, LAY_CHECKED: false} //其它参数在此省略
                , {field: 'roleId', title: '角色编号', width: 120, align: 'center'}
                , {field: 'roleName', title: '角色名称', width: 350, align: 'center'}
                , {title: '操作', fixed: 'right', width: 160, align: 'center', toolbar: '#bar'}
            ]]
            , page: true
            , limits: [5, 10, 15]
            , limit: 10 //默认采用10
            , done: function (res, curr, count) {
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                //console.log(res);
                //得到当前页码
                //console.log(curr);
                $("#curPageIndex").val(curr);
                //得到数据总量
                //console.log(count);
            }
        });
        $("#add").click(function () {
            layer.open({
                type: 1,
                title: '添加角色',
                shade: 0.4,  //阴影度
                fix: false,
                shadeClose: true,
                maxmin: false,
                area: ['400px;', '450px;'],    //窗体大小（宽,高）
                content: $('#addData'),
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                    layero.addClass('layui-form');//添加form标识
                    layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
                    form.render();
                    body.find('#hidValue').val(index); //将本层的窗口索引传给子页面层的hidValue中
                },
                btn: ['添加', '取消'],
                yes: function (index, layero) {
                    form.on('submit(fromContent)', function (data) {
                        $.post('permission/addRole', $('#addRoleForm').serialize(), function (res) {
                            if (res.code == 0) {
                                parent.layer.msg('添加角色成功！', {icon: 1, shade: 0.4, time: 1000});
                                $("#search").click();
                                $("#addRoleForm")[0].reset();
                                layui.form.render();
                                layer.close(index);
                            } else {
                                parent.layer.msg(res.msg, {icon: 5, shade: 0.4, time: 1000});
                            }
                        });
                    })
                }
            });
        });
        //#region --------------搜索----------------
        $("#search").click(function () {
            var word = $("#keyword").val();
            tableIns.reload({
                where: {
                    keyword: word
                }, page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });
        //工具条事件监听
        table.on('tool(type)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            if (layEvent === 'edit') { //编辑
                layer.open({
                    type: 1,
                    title: '编辑角色信息',
                    shade: 0.4,  //阴影度
                    fix: false,
                    shadeClose: true,
                    maxmin: false,
                    area: ['400px;', '450px;'],    //窗体大小（宽,高）
                    content: $('#formData'),
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                        layero.addClass('layui-form');//添加form标识
                        layero.find('.layui-layer-btn0').attr('lay-filter', 'editFormContent').attr('lay-submit', '');//将按钮弄成能提交的
                        form.render();
                        $("#showRoleId").val(data.roleId);
                        $("#showRoleNmae").val(data.roleName);
                        var funs = data.roleFuns;
                        $.ajax({
                            type: "POST",
                            url: "permission/findAllFuns",
                            success: function (res) {
                                var str = "";
                                for (var i = 0; i < res.data.length; i++) {
                                    var flag = false;
                                    for (var j = 0; j < funs.length; j++) {
                                        if (funs[j].funId == res.data[i].funId) {
                                            str = str + "<input type='checkbox' value='" + res.data[i].funId + "' checked name='funId' title='" + res.data[i].funName + "' lay-skin=\"primary\">";
                                            flag = true;
                                        }
                                    }
                                    if(!flag){
                                        str = str + "<input type='checkbox' value='" + res.data[i].funId + "' name='funId' title='" + res.data[i].funName + "' lay-skin=\"primary\">";
                                    }
                                }
                                $(".editFunList").html(str);
                                layui.form.render();
                            }
                        });
                        body.find('#hidValue').val(index); //将本层的窗口索引传给子页面层的hidValue中
                    },
                    btn: ['修改', '取消'],
                    yes: function (index, layero) {
                        form.on('submit(editFormContent)', function (data) {
                            $.post('permission/updateRole', $('#roleForm').serialize(), function (res) {
                                if (res.code == 0) {
                                    parent.layer.msg('编辑角色成功！', {icon: 1, shade: 0.4, time: 1000});
                                    $("#search").click();
                                    $("#roleForm")[0].reset();
                                    layui.form.render();
                                    layer.close(index);
                                } else {
                                    parent.layer.msg(res.msg, {icon: 5, shade: 0.4, time: 1000});
                                }
                            });
                        })
                    }
                });
            } else if (layEvent === 'delete') {
                layer.confirm('是否删除该角色？', {
                    btn: ['确认', '取消'] //可以无限个按钮
                    , btn1: function (index, layero) {
                        $.ajax({
                            type: "POST",
                            url: "permission/deleteRole",
                            data: "roleId=" + data.roleId,
                            success: function (res) {
                                if (res.code == 0) {
                                    parent.layer.msg('删除成功', {icon: 1, shade: 0.4, time: 1000});
                                } else {
                                    parent.layer.msg('删除失败', {icon: 5, shade: 0.4, time: 1000});
                                }
                            }
                        });
                        $(tr).remove();
                        layer.close(index);
                    }
                });
            }
        });
    });
    window.onload = function () {
        $.ajax({
            type: "POST",
            url: "permission/findAllFuns",
            success: function (data) {
                var str = "";
                for (var i = 0; i < data.data.length; i++) {
                    str = str + "<input type='checkbox' value='" + data.data[i].funId + "' name='funId' title='" + data.data[i].funName + "' lay-skin=\"primary\">";
                }
                $(".funslist").html(str);
            }
        });
    }
</script>
</body>
</html>